#include "Condition.h"

using namespace ddserver::thread;

Condition::Condition()
{
    pthread_cond_init(&m_cond, NULL);
}

Condition::~Condition()
{
    pthread_cond_destroy(&m_cond);
}

int Condition::wait(Mutex* mutex)
{
    return pthread_cond_wait(&m_cond, &(mutex->m_mutex));
}

int Condition::timedwait(Mutex *mutex,long milliseconds)
{
    int rc = 0;
    struct timespec abstime;
    struct timeval tv;
    gettimeofday(&tv,NULL);
    abstime.tv_sec = tv.tv_sec + milliseconds/100;
    abstime.tv_nsec = tv.tv_usec * 1000 + (milliseconds % 1000)*1000000;
    if (abstime.tv_nsec >= 1000000000)
    {
        abstime.tv_nsec -= 1000000000;
        abstime.tv_sec++;
    }
    
    if (0!= pthread_cond_timedwait(&m_cond, &(mutex->m_mutex), &abstime))
    {
        return -1;
    }
    return 0;
}

int Condition::signal()
{
    return pthread_cond_signal(&m_cond);
}

int Condition::broadcast()
{
    return pthread_cond_broadcast(&m_cond);
}


